﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Common;
using StoragePeriod.Data;
using StoragePeriod.Web.Common;
using System.Text;
using StoragePeriod.Model.StorageForecast;
using StoragePeriod.BLL.StorageForecast;
using StoragePeriod.BLL.RawDict;
using StoragePeriod.Model.RawDict;

namespace StoragePeriod.Web.StorageForecast.QualityEstimates
{
    public partial class QualityEstimatesList : SecurityPage
    {
        T_RawMaterial tRawMaterial = new T_RawMaterial();   //原料操作
        T_QualityCalculateMove tQualityCalculateMove = new T_QualityCalculateMove(); //品质估算模型
        T_QualityCalculateLog tQualityCalculateLog = new T_QualityCalculateLog();//品质估算日志
        T_QualityResult tQualityResult = new T_QualityResult();//品质估算结果
        T_ImgView tImgView = new T_ImgView();//品质估算图片预览
        T_RawMaterialType tRawMaterialType = new T_RawMaterialType();//原料类别操作
        T_QuotaPrompt tQuotaPrompt = new T_QuotaPrompt();//指标说明

        public override string PrivCode()
        {
            return "fd31e9e19a15dc48";
        }

        //绑定下拉菜单
        private void DropBandingSearch()
        {
            List<OperationTeam> OperationList = OperationTeam.Where("ParentId=@0", 0).OrderByDescending(p => p.id).ToList();
            this.Drop_OperationSearch.DataSource = OperationList;
            this.Drop_OperationSearch.DataValueField = "id";
            this.Drop_OperationSearch.DataTextField = "OTName";
            this.Drop_OperationSearch.DataBind();
            this.Drop_OperationSearch_SelectedIndexChanged(null, null);

            List<RawMaterialType> TargetsList = RawMaterialType.Where("ParentId=@0 and TypeInfoid=@1", 0, Convert.ToInt32(EnumData.TypeInfo.预测指标)).OrderByDescending(p => p.id).ToList();
            this.Drop_Targets.DataSource = TargetsList;
            this.Drop_Targets.DataValueField = "id";
            this.Drop_Targets.DataTextField = "TypeName";
            this.Drop_Targets.DataBind();

            this.Drop_Targets_SelectedIndexChanged(null, null);

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            BindTreeView();
            DropBandingSearch();
            LeftLable.Text = "现有品质估算";

            SYS_Users md = SYS_Users.Where("UserCode=@0", User.Identity.Name).First();
            OperationTeam team = OperationTeam.Where("id=@0", Convert.ToInt32(md.UserType)).First();
            this.Drop_OperationSearch.SelectedValue = team.ParentId.ToString();
            this.Drop_OperationSearch_SelectedIndexChanged(null, null);
            this.Drop_TeamSearch.SelectedValue = team.id.ToString();
            if (md.RoleName != "管理员")
            {
                this.Drop_OperationSearch.Enabled = false;
                this.Drop_TeamSearch.Enabled = false;
            }
            this.LoadPriv();
        }

        //加载权限控件
        private void LoadPriv()
        {
            this.Btn_AddImg.Visible = IsExisPriv("dd10b3c59866e745");
            this.Btn_DelImg.Visible = IsExisPriv("722fae95320532ab");
        }

        //绑定原料树
        public void BindTreeView()
        {
            NutrientsTree.Nodes.Clear();
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0 and Typeinfoid=@1", 0, Convert.ToInt32(EnumData.TypeInfo.食品检测)).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.EToString(),
                    Target = "Parent",
                };
                childNode = GetRawByTypeId(childNode);
                NutrientsTree.Nodes.Add(childNode);
            });
            SysTree_SelectedNodeChanged(null, null);
        }
        private TreeNode GetRawByTypeId(TreeNode tn)
        {
            int Pid = int.Parse(tn.Value);
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0", Pid).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.ToString(),
                    Target = "Parent"
                };
                childNode = GetRawByTypeId(childNode);
                tn.ChildNodes.Add(childNode);
            });

            int TypeId = int.Parse(tn.Value);
            List<E_RawMaterial> rmlist = rmlist = tRawMaterial.GetModelList("PeriodTypeStorageID =" + TypeId);

            rmlist.ForEach(a =>
            {
                TreeNode rnod = new TreeNode()
                {
                    Text = a.RAWName,
                    Value = a.id.EToString(),
                    Target = "Child"
                };
                tn.ChildNodes.Add(rnod);
            });
            return tn;
        }

        protected void SysTree_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn != null && tn.Target == "Child")
            {
                this.lbl_SelRawName.Text = "";//已选原料
                this.TxT_FactValue.Text = "";//实际值
                this.lbl_SelRawName.Text = "已选原料：" + tn.Text;//原料名称
                this.HidRawID.Value = tn.Value;//原料ID
                this.txt_Temperature.Text = "";
                this.txt_licunTime.Text = "";
                this.txt_ReferenceValue.Text = "";
                this.TxT_FactValue.Text = "";
                this.txt_centent.Text = "";
                //获取参考值

                //绑定品质图片
                this.RepImgListBind();

                //加载对应指标
                this.Drop_Targets_SelectedIndexChanged(null, null);
            }
        }

        //删除 贮存知识
        protected void btn_Del_Click(object sender, EventArgs e)
        {
            //TreeNode tn = this.NutrientsTree.SelectedNode;
            //int id = 0;
            //Int32.TryParse(tn.Value, out id);
            //if (tn.Target == "Child")
            //{
            //    IntroduceStorage.Delete("id == @0", id);
            //    string script = "<script type='text/javascript'>alert('删除成功！');</script>";
            //    ScriptManager.RegisterStartupScript(this, Page.GetType(), "", script, false);
            //    BindTreeView();
            //}
            //else
            //{
            //    string script = "<script type='text/javascript'>alert('您不能删除分类！');</script>";
            //    ScriptManager.RegisterStartupScript(this, Page.GetType(), "", script, false);
            //}
        }

        //查询原料树
        protected void btn_search_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Txt_Search.Text))
            {
                return;
            }
            for (int i = 0; i < NutrientsTree.Nodes.Count; i++)
            {
                for (int ii = 0; ii < NutrientsTree.Nodes[i].ChildNodes.Count; ii++)
                {
                    if (NutrientsTree.Nodes[i].ChildNodes[ii].Text.Contains(Txt_Search.Text))
                    {
                        TreeNode node = NutrientsTree.Nodes[i].ChildNodes[ii];
                        string text = node.Text;
                        node.Text = HttpUtility.HtmlDecode(node.Text).Replace(Txt_Search.Text, "<span class='Red'>" + Txt_Search.Text + "</span>");
                    }
                }
            }
        }

        //加载班组
        protected void Drop_OperationSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.Drop_OperationSearch.SelectedItem != null)
            {
                int ParentId = Convert.ToInt32(this.Drop_OperationSearch.SelectedValue);
                List<OperationTeam> TeamList;
                if (ParentId == -1)
                {
                    TeamList = new List<OperationTeam>();
                }
                else
                {
                    TeamList = OperationTeam.Where("ParentId=@0", ParentId).ToList();
                }
                this.Drop_TeamSearch.DataSource = TeamList;
                this.Drop_TeamSearch.DataValueField = "id";
                this.Drop_TeamSearch.DataTextField = "OTName";
                this.Drop_TeamSearch.DataBind();
            }
        }

        //加载二级指标
        protected void Drop_Targets_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.Drop_Targets.SelectedItem != null&&this.HidRawID.Value!="")
            {
                int RawID = int.Parse(this.HidRawID.Value);
                E_RawMaterial eRawMaterial = tRawMaterial.GetModel(RawID);
                int RawTypeID = int.Parse(eRawMaterial.PeriodTypeStorageID.ToString());
                E_RawMaterialType eRawMaterialType = tRawMaterialType.GetModel(RawTypeID);
                if (eRawMaterialType.ParentId > 0)
                {
                    this.GetRawParentTtypeID(ref RawTypeID);
                }
                int ParentId = Convert.ToInt32(this.Drop_Targets.SelectedValue);
                List<E_RawMaterialType> list = tRawMaterialType.GetModelList("ParentId=" + ParentId + " and RawTypePath like '%|" + RawTypeID + "%|'").ToList();
                this.Drop_TargetsInfo.DataSource = list;
                this.Drop_TargetsInfo.DataValueField = "id";
                this.Drop_TargetsInfo.DataTextField = "TypeName";
                this.Drop_TargetsInfo.DataBind();

                this.Drop_TargetsInfo_SelectedIndexChanged(null, null);
            }
            //加载默认指定JS
            UtilityUI.Load(this.UpdatePanel1, "SetShowPage();");
        }

        //获取根类别ID
        private void GetRawParentTtypeID(ref int RawTypeID)
        {
            E_RawMaterialType eRawMaterialType = tRawMaterialType.GetModel(RawTypeID);
            RawTypeID = int.Parse(eRawMaterialType.ParentId.ToString());
            E_RawMaterialType Temp = tRawMaterialType.GetModel(RawTypeID);
            if (Temp.ParentId > 0)
            {
                this.GetRawParentTtypeID(ref RawTypeID);
            }
        }

        //保存图片
        protected void btn_SaveImg_Click(object sender, EventArgs e)
        {
            string strFileName = this.file_ImgPath.FileName;
            string[] strS = strFileName.Split('.');
            string strName = Guid.NewGuid() + "." + strS[strS.Length - 1];
            this.file_ImgPath.SaveAs(MapPath("~/UpLoad/") + strName);

            E_ImgView eImgView = new E_ImgView();
            eImgView.RawID = Convert.ToInt32(this.HidRawID.Value);
            eImgView.ImgTypeID = 1;//品质变化图
            eImgView.Imgname = this.txt_addImgName.Text.Trim();
            eImgView.ImgPath = strName;
            eImgView.UpLoadTime = DateTime.Now;
            eImgView.UpLoadUserID = CurrentUser.id;
            eImgView.UpLoadUserName = CurrentUser.UserName;
            eImgView.Description = this.txt_addImgDescription.Text.Trim();
            tImgView.Add(eImgView);

            this.HidPageIndex.Value = "1";
            this.RepImgListBind();
        }

        //删除图片
        protected void Btn_DelImg_Click(object sender, EventArgs e)
        {
            int ImgID = Convert.ToInt32(this.HidImgID.Value);
            if (ImgID != 0)
            {
                tImgView.Delete(ImgID);
            }
            this.HidPageIndex.Value = "1";
            this.HidIsNext.Value = "1";
            this.RepImgListBind();
        }

        //绑定图片列表
        private void RepImgListBind()
        {
            int RawID = Convert.ToInt32(this.HidRawID.Value);
            int pageindex = Convert.ToInt32(this.HidPageIndex.Value);
            int pagesize = 5;

            //获取品质预览图片集合
            List<E_ImgView> list = tImgView.GetModelList("RawID=" + RawID + " and ImgTypeID=1");
            int rowcount = list.Count();
            this.HidPageCount.Value = ((rowcount % pagesize > 0) ? rowcount / pagesize + 1 : rowcount / pagesize).ToString();



            this.RepImgList.DataSource = list.OrderByDescending(p => p.UpLoadTime).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
            this.RepImgList.DataBind();

            //加载默认指定JS
            UtilityUI.Load(this.UpdatePanel1, "SetShowPage();");
        }

        //上一页
        protected void Btn_List_Prve_Click(object sender, EventArgs e)
        {
            int pageindex = Convert.ToInt32(this.HidPageIndex.Value);
            int pagecount = Convert.ToInt32(this.HidPageCount.Value);

            if (pageindex > 1)
            {
                this.HidPageIndex.Value = (pageindex - 1).ToString();
                this.RepImgListBind();
            }
        }

        //下一页
        protected void Btn_List_Next_Click(object sender, EventArgs e)
        {
            int pageindex = Convert.ToInt32(this.HidPageIndex.Value);
            int pagecount = Convert.ToInt32(this.HidPageCount.Value);

            if (pageindex < pagecount)
            {
                this.HidPageIndex.Value = (pageindex + 1).ToString();
                this.RepImgListBind();
            }
        }

        //估算品质
        protected void Btn_Calulate_Click(object sender, EventArgs e)
        {
            int RawID = Convert.ToInt32(this.HidRawID.Value);   //原料ID
            int QuotaID = int.Parse(this.Drop_TargetsInfo.SelectedValue);//指标ID
            decimal T = decimal.Parse(this.txt_Temperature.Text.Trim()) + 273; //库存温度 K=℃+273
            decimal t = decimal.Parse(this.txt_licunTime.Text.Trim());//库存时间
            E_QualityCalculateMove md = tQualityCalculateMove.GetModelList("RawID=" + RawID + " and QuotaID=" + QuotaID).FirstOrDefault();
            if (md == null)
            {
                UtilityUI.Alert(this.UpdatePanel1, "没有对应指标下的估算模型！");
                return;
            }

            try
            {
                int CalculateTypeID = (md.CalculateTypeID == null ? 1 : int.Parse(md.CalculateTypeID.ToString()));//计算公式类型
                decimal Y = 0; //品质结果
                decimal Y_1 = 0;//Vc下降率
                switch (CalculateTypeID)
                {
                    case 1://Y（品质）=M(+|-)te次方((正|负)N/T+Z) 其中:e=2.71828  t:贮存时间(d); Y:品质指标量  T：贮存温度（K）,其中K=℃+273
                        decimal eResult = 0; //e N次方后的结果
                        decimal Th = 0;//次方数
                        Th = Convert.ToDecimal(md.N * (Convert.ToBoolean(md.IsNegative) ? -1 : 1) / T + md.Z); //计算次方后的数
                        eResult = Convert.ToDecimal((Math.Pow(2.71828, Convert.ToDouble(Th))).ToString("f8"));//e次方后的结果
                        Y = Convert.ToDecimal(md.M + (Convert.ToInt32(md.Connector) == 1 ? 1 : -1) * t * eResult);
                        break;
                    case 2: //Y(失重率)=t*exp(M-N/T)
                        Y = t * Convert.ToDecimal(Math.Exp(Convert.ToDouble(md.M - md.N / T)));
                        break;
                    case 3: //Y(Vc含量)=M-t*exp(N-Z/T)
                        Y = Convert.ToDecimal(md.M) - t * Convert.ToDecimal(Math.Exp(Convert.ToDouble(md.N - md.Z / T)));
                        Y_1 = Convert.ToDecimal((md.A - Y) * 100 / md.B);//Vc下降率
                        break;
                    case 4://Y(Vc含量)=exp{M-t*exp(N-Z/T)}
                        Y = Convert.ToDecimal(Math.Exp(Convert.ToDouble(md.M) - Convert.ToDouble(t) * Convert.ToDouble(Math.Exp(Convert.ToDouble(md.N - md.Z / T)))));
                        Y_1= Convert.ToDecimal((md.A - Y) * 100 / md.B);//Vc下降率
                        break;
                    case 5://Y(Vc下降率)=(A-Y(Vc含量))*100/B 已经合并到 3 和 4 里面去了
                        decimal vc = 0; //获取对应的值
                        if (this.txt_Vc.Text.Trim() != "")
                        {
                            vc = Convert.ToDecimal(this.txt_Vc.Text.Trim());
                        }
                        Y = Convert.ToDecimal((md.A - vc) * 100 / md.B);
                        break;
                    case 6://C(失重率)=M*10(N次方)*exp(-Z/T)*t
                        Y = Convert.ToDecimal(Convert.ToDouble(md.M) * Math.Pow(10, Convert.ToDouble(md.N)) * Math.Exp(Convert.ToDouble((md.Z * -1) / T)) * Convert.ToDouble(t));
                        break;
                    case 7://Y(主观评分)=10-t*exp(M-N/T)
                        Y = Convert.ToDecimal(10 - Convert.ToDouble(t) * Math.Exp(Convert.ToDouble(md.M - md.N / T)));
                        break;
                    case 8://C(感官评分)=10-M*10(N次方)*exp(-Z/T)*t
                        Y = Convert.ToDecimal(10 - Convert.ToDouble(md.M) * Math.Pow(10, Convert.ToDouble(md.N)) * Math.Exp(Convert.ToDouble((md.Z * -1) / T)) * Convert.ToDouble(t));
                        break;
                    case 9://Y（水果Vc含量）=M*exp(-[N*exp(-Z/T)*t])
                        Y = Convert.ToDecimal(Convert.ToDouble(md.M) * Math.Exp((-1 * Convert.ToDouble(md.N) * Math.Exp(Convert.ToDouble(md.Z * -1 / T)) * Convert.ToDouble(t))));
                        Y_1= Convert.ToDecimal((md.A - Y) * 100 / md.B);//Vc下降率
                        break;
                }

                /*
                this.TxT_FactValue.Text = Y.ToString("f2"); //实际值复制
                this.txt_centent.Text += "库存温度：" + (T - 273) + "(℃)，存放时间：" + t + "(天)，Y(" + this.Drop_TargetsInfo.SelectedItem.Text + "):" + Y.ToString("f2") + "；   ";
                if (CalculateTypeID == 3 || CalculateTypeID == 4)
                {
                    this.txt_centent.Text += "Y（Vc下降率）：" + Y_1.ToString("f2");
                }
                */
                if (CalculateTypeID == 3 || CalculateTypeID == 4 || CalculateTypeID == 9)
                {
                    this.TxT_FactValue.Text = Y_1.ToString("f2"); //实际值复制
                    this.txt_centent.Text += " 库存温度：" + (T - 273) + "(℃)，存放时间：" + t + "(天)，Y(VC含量):" + Y.ToString("f2") + "，Y(" + this.Drop_TargetsInfo.SelectedItem.Text + "):" + Y_1.ToString("f2") + "；   ";
                }
                else
                {
                    this.TxT_FactValue.Text = Y.ToString("f2"); //实际值复制
                    this.txt_centent.Text += " 库存温度：" + (T - 273) + "(℃)，存放时间：" + t + "(天)，Y(" + this.Drop_TargetsInfo.SelectedItem.Text + "):" + Y.ToString("f2") + "；   ";
                }

                #region 加载指标说明
                string strPrompt = "";//说明内容
                E_RawMaterial eRawMaterial = tRawMaterial.GetModel(RawID);
                int RawTypeID = int.Parse(eRawMaterial.PeriodTypeStorageID.ToString());
                E_RawMaterialType eRawMaterialType = tRawMaterialType.GetModel(RawTypeID);
                if (eRawMaterialType.ParentId > 0)
                {
                    this.GetRawParentTtypeID(ref RawTypeID);
                }

                List<E_QuotaPrompt> listPrompt = tQuotaPrompt.GetModelList("QuotaID=" + QuotaID + " and RawTypeID=" + RawTypeID);
                if (listPrompt != null && listPrompt.Count > 0)
                {
                    foreach (E_QuotaPrompt item in listPrompt)
                    {
                        decimal StartNum = Convert.ToDecimal(item.StartNum);
                        decimal EndNum = Convert.ToDecimal(item.EndNum);
                        if (Y >= StartNum && Y <= EndNum) //判断是否在区间内
                        {
                            strPrompt += item.Prompt;
                            continue;
                        }
                    }
                }
                if (strPrompt.Length > 0)
                {
                    strPrompt = "  提示：" + strPrompt;
                }
                this.txt_centent.Text += strPrompt;
                #endregion

                //添加计算日志
                E_QualityCalculateLog eQualityCalculateLog = new E_QualityCalculateLog();
                eQualityCalculateLog.RawID = RawID;
                eQualityCalculateLog.RawName = this.NutrientsTree.SelectedNode.Text;
                eQualityCalculateLog.QuotaID = QuotaID;
                eQualityCalculateLog.QuotaName = this.Drop_TargetsInfo.SelectedItem.Text;
                eQualityCalculateLog.CalculateResult = this.txt_centent.Text;
                eQualityCalculateLog.AddTime = DateTime.Now;
                eQualityCalculateLog.CalculateTypeID = 1;//估算类型ID（1：品质估算、2：贮存期预测、3：贮存条件选择）
                eQualityCalculateLog.OAreaID = int.Parse(this.Drop_OperationSearch.SelectedValue); //作业区ID
                eQualityCalculateLog.TeamID = int.Parse(this.Drop_TeamSearch.SelectedValue); //班组ID
                tQualityCalculateLog.Add(eQualityCalculateLog);

                //加载默认指定JS
                UtilityUI.Load(this.UpdatePanel1, "SetShowPage();");
            }
            catch(Exception ex)
            {
                UtilityUI.Alert(this.UpdatePanel1, ex.Message);
                return;
            }
        }
        
        //保存评估结果
        protected void Btn_SaveCalulate_Click(object sender, EventArgs e)
        {
            int RawID = Convert.ToInt32(this.HidRawID.Value);   //原料ID
            int QuotaID = int.Parse(this.Drop_TargetsInfo.SelectedValue);//指标ID
            E_QualityResult eQualityResult = new E_QualityResult();
            eQualityResult.RawID = RawID;
            eQualityResult.RawName = this.NutrientsTree.SelectedNode.Text;
            eQualityResult.QuotaID = QuotaID;
            eQualityResult.QuotaName = this.Drop_TargetsInfo.SelectedItem.Text;
            eQualityResult.CalculateResult = this.txt_centent.Text;
            eQualityResult.AddTime = DateTime.Now;
            eQualityResult.CalculateTypeID = 1;//估算类型ID（1：品质估算、2：贮存期预测、3：贮存条件选择）
            eQualityResult.OAreaID = int.Parse(this.Drop_OperationSearch.SelectedValue); //作业区ID
            eQualityResult.TeamID = int.Parse(this.Drop_TeamSearch.SelectedValue); //班组ID
            tQualityResult.Add(eQualityResult);

            //加载默认指定JS
            UtilityUI.Load(this.UpdatePanel1, "SetShowPage();alert('保存成功！')");
            //UtilityUI.Alert(this.UpdatePanel1, "保存成功！");
        }

        //二级指标选择
        protected void Drop_TargetsInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool IsShow = false;
            if (this.HidRawID.Value != "" && this.Drop_TargetsInfo.SelectedItem != null)
            {
                //int RawID = Convert.ToInt32(this.HidRawID.Value);   //原料ID
                //int QuotaID = int.Parse(this.Drop_TargetsInfo.SelectedValue);//指标ID
                //E_QualityCalculateMove md = tQualityCalculateMove.GetModelList("RawID=" + RawID + " and QuotaID=" + QuotaID).FirstOrDefault();
                //if (md != null)
                //{
                //    if (md.CalculateTypeID != null && int.Parse(md.CalculateTypeID.ToString()) == 5)
                //    {
                //        IsShow = true;
                //    }
                //}
            }
            this.Pan_Vc.Visible = IsShow;
            //加载默认指定JS
            UtilityUI.Load(this.UpdatePanel1, "SetShowPage();");
        }
    }
}